package cn.ww.conf;

import javax.annotation.Resource;

import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import cn.ww.filter.TokenFilter;

@EnableWebSecurity(debug = true) // 启动SpringSecurity过滤器链
public class SecurityConfJwt extends WebSecurityConfigurerAdapter {
    
    @Resource
    private TokenFilter tokenFilter;
    
    
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(passwordEncoder())
        .withUser("aaa").password("123").roles("USER")
        .and().withUser("bbb").password("123").roles("ADMIN");
    }
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/api/user/login", "/api/user/register").permitAll()
        .antMatchers("/product/add").hasRole("ADMIN")
        .antMatchers("/product/update").hasRole("ADMIN")
        .antMatchers("/product/delete").hasRole("ADMIN")
        .antMatchers("/product/list").hasRole("USER")
        .anyRequest().authenticated()
        .and().csrf().disable();
        // 关闭 Session
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        // 添加拦截器
        http.addFilterBefore(tokenFilter, UsernamePasswordAuthenticationFilter.class);
        // 禁用缓存
        http.headers().cacheControl();

    }
    
    


    // 为学习测试方便,用明文储存密码
    @Bean
    public PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }

}
